package com.example.its2021606134chh.DAModule;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.its2021606134chh.R;
import com.example.its2021606134chh.TrafficViolationModule.CarPeccancys;
import com.example.its2021606134chh.TrafficViolationModule.CarSQLiteOpenHelper;
import com.example.its2021606134chh.TrafficViolationModule.TVSearchResultsActivity;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RepeatedTVFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RepeatedTVFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "title";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private ColumnChartView columnChartRepeated;
    private ColumnChartData mColumnChartData;    //柱状图数据
    public final static String[] xDate = {"1-2条违章", "3-5条违章", "5条以上违章"}; //x
    public RepeatedTVFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RepeatedTVFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RepeatedTVFragment newInstance(String param1, String param2) {
        RepeatedTVFragment fragment = new RepeatedTVFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_repeated_t_v, container, false);
        columnChartRepeated = (ColumnChartView) view.findViewById(R.id.columnChartRepeated);

        CarSQLiteOpenHelper openHelper;
        SQLiteDatabase database;
        openHelper = new CarSQLiteOpenHelper(getContext(), "CarPeccancy.db", null, 1);
        database = openHelper.getReadableDatabase();
        Set<String> stringSet = new HashSet<String>();//用Set存放不同的字符串
        Map<String, Integer> stringMap = new HashMap<String, Integer>();//用Map记录相同的元素的个数
        List<String> carnumbers = new ArrayList<String>();
        String sCarNum;
        try (Cursor cursor = database.query("carpeccancy", null, null, null, null, null, null)) {
            if (cursor.moveToFirst()) {
                do {
                    String carnumber = cursor.getString(1);
                    carnumbers.add(carnumber);
                } while (cursor.moveToNext());
            }
        } catch (SQLException ignored) {
            Toast.makeText(getContext(), "没有查询到违章数据！", Toast.LENGTH_SHORT).show();
        } finally {
            database.close();
        }

        for (int i = 0; i < carnumbers.size(); i++) {
            //取出数组中的数据
            sCarNum = carnumbers.get(i);
            //如果Set集合里面有同样的数据，就用Map记录这个数据个数+1
            if (stringSet.contains(sCarNum)) {
                stringMap.put(sCarNum, stringMap.get(sCarNum) + 1);
            } else {
            //否则，如果Set里面没有相同的数据，就放进Set里面，然后用Map记录这个数据个数为1
                stringSet.add(sCarNum);//添加不同的数据
                stringMap.put(sCarNum, 1);//个数记录为1
            }
        }
        int oneToTwo = 0;
        int threeToFive = 0;
        int overFive = 0;
        int allNum = 0;
        //因为Set中元素是不相同的Set 集合的大小就是不同元素的个数；Map存放的是每个元素在字符串数组的个数
        for (String s : stringSet) {
            if (stringMap.get(s) >= 1 && stringMap.get(s) <= 2) {
                oneToTwo++;
            } else if (stringMap.get(s) >= 3 && stringMap.get(s) <= 5) {
                threeToFive++;
            } else if (stringMap.get(s) >5) {
                overFive++;
            }
        }
        allNum = stringSet.size();

        BigDecimal b1  = BigDecimal.valueOf((float) oneToTwo / (float) allNum * 100);
        BigDecimal b2  = BigDecimal.valueOf((float) threeToFive / (float) allNum * 100);
        BigDecimal b3  = BigDecimal.valueOf((float) overFive / (float) allNum * 100);
        float f1 = b1.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        float f2 = b2.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        float f3 = b3.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        float[] score= {f1, f2, f3};//图表的数据点
//        Log.i("TAG", String.valueOf(f1));
//        Log.i("TAG", String.valueOf(f2));
//        Log.i("TAG", String.valueOf(f3));

        //颜色值
        List<Integer> color = new ArrayList<>();
        color.add(Color.parseColor("#009BDB"));
        color.add(Color.parseColor("#85B74F"));
        color.add(Color.parseColor("#ff0000"));

        List<Column> columnList = new ArrayList<>(); //柱子列表
        List<SubcolumnValue> subcolumnValueList;     //子柱列表（即一个柱子，因为一个柱子可分为多个子柱）
        List<AxisValue> axisValues = new ArrayList<>();//自定义横轴坐标值
        for (int i = 0; i < 3; ++i) {
            subcolumnValueList = new ArrayList<>();
            subcolumnValueList.add(new SubcolumnValue(score[i], color.get(i)));

            Column column = new Column(subcolumnValueList);
            columnList.add(column);
            column.setHasLabels(true);  //设置列标签
//            //只有当点击时才显示列标签
//            column.setHasLabelsOnlyForSelected(true);
            //设置坐标值
            axisValues.add(new AxisValue(i).setLabel(xDate[i]));
        }

        mColumnChartData = new ColumnChartData(columnList);

        /*===== 坐标轴相关设置 =====*/
        //将自定义x轴显示值传入构造函数
        Axis axisX = new Axis(axisValues);
        Axis axisY = new Axis().setHasLines(true);
//        axisX.setName("Axis X");    //设置横轴名称
//        axisY.setName("Axis Y");    //设置竖轴名称
        mColumnChartData.setAxisXBottom(axisX); //设置横轴
        mColumnChartData.setAxisYLeft(axisY);   //设置竖轴

        //以上所有设置的数据、坐标配置都已存放到mColumnChartData中，接下来给mColumnChartView设置这些配置
        columnChartRepeated.setColumnChartData(mColumnChartData);
        Viewport v = columnChartRepeated.getMaximumViewport();
        v.top = 103;
        columnChartRepeated.setCurrentViewport(v);

        return view;
    }
}